package com.sofwin.realm;

import com.sofwin.pojo.SysUser;
import com.sofwin.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @packageName: com.sofwin.realm
 * @user: andyliu
 * @date: 2023/1/5 16:43
 * @email 115176513@qq.com
 * @description: TODO
 */
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
       // subject.login 直接调用 doGetAuthenticationInfo
        UsernamePasswordToken token2 = (UsernamePasswordToken) token;
        // 客户端输入的用户名和密码
        String loginName = token2.getPrincipal().toString();
        String loginPwd = new String(token2.getPassword());
        // 密码最后需要加密码    用户输入的密码和数据库中的密码
        SysUser sysUser = userService.queryUserByLoginNameAndPwd(loginName, "");
        if(sysUser==null){
            throw new UnknownAccountException();
        }
        if(sysUser!=null && sysUser.getStatus()==1){
            throw new LockedAccountException();
        }
        return new SimpleAuthenticationInfo(loginName, sysUser.getLoginPwd(),this.getName());
    }
}
